package test;

import com.alibaba.nacos.api.naming.NamingService;
import com.xw.echo.core.client.EchoClusterClient;
import com.xw.echo.core.nacos.client.NacosClientManager;
import com.xw.echo.core.service.UserService;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class test {
    public static void main(String[] args) throws InterruptedException {
        NamingService namingService = NacosClientManager.getNamingService("47.97.81.253:8848", "nacos", "Wc233333");
        EchoClusterClient echoClusterClient = new EchoClusterClient("Server", namingService);
        /* echoClusterClient.setLoadBalancer(new RandomLoadBalance());*/
        UserService userService = (UserService) echoClusterClient.creatProxy(UserService.class);
        int totalCalls = 500; // 总调用次数
        int threadCount = 16; // 并发线程数
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        CountDownLatch latch = new CountDownLatch(totalCalls);
        AtomicLong totalDuration = new AtomicLong(0); // 累计所有请求耗时
        AtomicLong maxDuration = new AtomicLong(0);
        AtomicLong minDuration = new AtomicLong(Long.MAX_VALUE);

        long testStartTime = System.currentTimeMillis(); // 性能测试开始时间

        // 使用固定线程池执行异步登录操作
        for (int i = 0; i < totalCalls; i++) {
            // 提交任务到线程池执行
            executor.submit(() -> {
                // 记录每个任务的开始时间
                long startTime = System.currentTimeMillis();
                // 异步执行登录操作
                userService.loginAsync("世界");
                try {
                    // 计算任务执行时间
                    long duration = System.currentTimeMillis() - startTime;
                    // 累加总时间
                    totalDuration.addAndGet(duration);
                    // 更新最大耗时
                    maxDuration.updateAndGet(prev -> Math.max(prev, duration));
                    // 更新最小耗时
                    minDuration.updateAndGet(prev -> Math.min(prev, duration));
                } catch (Exception e) {
                    // 打印异常信息
                    e.printStackTrace();
                } finally {
                    // 任务完成，计数器减一
                    latch.countDown();
                }
            });
        }

        latch.await(); // 等待所有请求完成
        long testEndTime = System.currentTimeMillis(); // 性能测试结束时间
        // 优雅关闭线程池
        executor.shutdown();
        try {
            // 等待所有任务完成或超时
            if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }

        long totalTestTime = testEndTime - testStartTime; // 总测试时间

        double tps = totalCalls / (totalTestTime / 1000.0);
        double avgDuration = totalDuration.get() / (double) totalCalls;

        System.out.println("========== 性能测试结果 ==========");
        System.out.println("总调用次数: " + totalCalls);
        System.out.println("并发线程数: " + threadCount);
        System.out.println("总耗时: " + totalTestTime + " ms");
        System.out.println("吞吐量(TPS): " + tps);
        System.out.println("平均响应时间: " + avgDuration + " ms");
        System.out.println("最大响应时间: " + maxDuration.get() + " ms");
        System.out.println("最小响应时间: " + minDuration.get() + " ms");
    }
}
